﻿using UnityEngine;
using UnityEngine.UI;

public class UITextLimit : MonoBehaviour
{
    public float MaxWidth;
    private float m_Width;
    private Text m_Text;
    private LayoutElement m_Element;

    void Start()
    {
        m_Text = GetComponentInChildren<Text>();
        m_Element = GetComponent<LayoutElement>();
        if (m_Element == null)
            m_Element = gameObject.AddComponent<LayoutElement>();
    }

    void Update()
    {

    }

    void LateUpdate()
    {
        if (MaxWidth > 0)
        {
            float width = m_Text.preferredWidth;
            if (width != m_Width)
            {
                m_Width = width;
                if (width > MaxWidth)
                    m_Element.preferredWidth = MaxWidth;
                else
                    m_Element.preferredWidth = width;
            }
        }
    }
}
